<template>
    <div class="exam" :style="{background: backgroundColor, color: fontColor}">
        <div class="exam-inner" v-if="isSubmit === 0">
            <h3>{{paperTitle}}</h3>
            <div class="qst_single" v-if="paper.qst_single">
                <h4>一、 单项选择题</h4>
                <dl
                    class="test-item qst-stem"
                    v-for="(test, index) in paper.qst_single"
                    :key="test.id"
                    :id="'single_' + (index + 1)"
                >
                    <dt class="inline clearfix">
                        <div class="pull-left">{{index + 1}}.&nbsp;</div>
                        <div class="pull-left text" v-html="test.qstStem"></div>
                        <div class="pull-left">({{test.score}}分)</div>
                    </dt>
                    <dd>
                        <div v-for="j in 4" :key="j">
                            <div class="inline option clearfix" v-if="test['opt' + j]">
                                <div class="label pull-left">
                                    <!-- <el-radio v-model="answer.qst_single[index][j-1]" :label="j" :name="'answer_' + index " >{{answerLabels[j - 1]}}</el-radio> -->
                                    <!-- <el-radio v-model="answer.qst_single[index]" :label="j" :name="'answer_' + index " >{{answerLabels[j - 1]}}</el-radio> -->
                                    <label class="radio">
                                        <input
                                            :name="'single_' + index"
                                            type="radio"
                                            :value="j"
                                            v-model="answer.qst_single[index][1]"
                                        >
                                        {{answerLabels[j - 1]}}&nbsp;
                                    </label>
                                </div>
                                <div class="text pull-left" v-html="test['opt' + j]"></div>
                            </div>
                        </div>
                    </dd>
                </dl>
            </div>
            <div class="qst_more" v-if="paper.qst_more">
                <h4>二、多项选择题</h4>
                <dl
                    class="test-item qst-stem"
                    v-for="(test, index) in paper.qst_more"
                    :key="'more_' + test.id"
                    :id="'more_' + (index + 1)"
                >
                    <dt class="inline clearfix">
                        <div class="pull-left">{{ paper.qst_single.length + index + 1}}.&nbsp;</div>
                        <div class="pull-left text" v-html="test.qstStem"></div>
                        <div class="pull-left">({{test.score}}分)</div>
                    </dt>
                    <dd>
                        <div v-for="j in 6" :key="j">
                            <div class="inline option clearfix" v-if="test['opt' + j]">
                                <div class="label pull-left">{{answerLabels[j - 1]}}.&nbsp;</div>
                                <div class="text pull-left" v-html="test['opt' + j]"></div>
                            </div>
                        </div>

                        <span v-for="j in 6" :key="'more_checkbox' + j">
                            <label class="checkbox" v-if="test['opt' + j]">
                                <input
                                    type="checkbox"
                                    :name="'more_' + index"
                                    :value="j + ''"
                                    v-model="answer.qst_more[test.id][j - 1]"
                                >
                                {{answerLabels[j - 1]}}&nbsp;
                            </label>
                        </span>
                    </dd>
                </dl>
            </div>
            <button @click="submitForm" v-loading.fullscreen.lock="fullscreenLoading">交卷</button>
        </div>
        <!-- 答题卡 -->
        <div class="answer-card" v-if="isSubmit === 0">
            <div class="time">剩余时间: {{formatSeconds(remainSecond) }}</div>
            <div class="title">答题卡</div>
            <div class="content">
                <div v-if="paper.qst_single">
                    <h5>单选题</h5>
                    <div class="num">
                        <a
                            :class="{active: answer.qst_single[i - 1][1]}"
                            v-for="i in paper.qst_single.length "
                            :key="i"
                            :href="'#single_' + i"
                        >{{i}}</a>
                    </div>
                </div>
                <div v-if="paper.qst_more">
                    <h5>多选题</h5>
                    <div class="num">
                        <a
                            v-for="(test, index) in paper.qst_more"
                            :key="index"
                            :class="{active: isMoreTestSelected(answer.qst_more[test.id])}"
                            :href="'#more_' + (index + 1)"
                        >{{ paper.qst_single.length + (index + 1) }}</a>
                    </div>
                </div>
            </div>背景颜色
            <el-color-picker v-model="backgroundColor" show-alpha></el-color-picker>字体颜色
            <el-color-picker v-model="fontColor" show-alpha></el-color-picker>
            <button @click="autoSaveForm">保存答案</button>
        </div>
        <div v-if="isSubmit === 1">
            <div class="box">
                {{userName}}
                成绩： {{sumScore}}分
                <el-link
                    type="primary"
                    v-if="analysisVisible === 1"
                    @click="$emit('closeTab'); $router.push({ path: '/exam/analysis?recordId=' + recordId })"
                >查看解析</el-link>
                用时： {{ formatSeconds(useTimeSecond)}}
                <el-button type="primary" @click="$emit('closeTab')">返回</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { setInterval, clearInterval } from "timers";
import { parse } from "path";
import { formatSeconds } from "@/utils";
export default {
    name: "exam-exam",
    data() {
        return {
            radio: 1,
            answerLabels: ["A", "B", "C", "D", "E", "F"],
            paper: {},
            paperId: "",
            paperTitle: "",
            answer: {
                qst_single: [["", ""]]
            },
            sumScore: 0, // 总成绩
            remainSecond: 0,
            countSecond: 0,
            len: 0,
            recordId: sessionStorage.currExamRecordId || null,
            // backgroundColor: "#f4f4f4",
            // backgroundColor: "#f9f9f9",
            backgroundColor: "#fff",
            fontColor: "#4f4f4f",
            realAnswers: {
                // 类型 ： { id: 答案， }
            },
            dialogVisible: false,
            isSubmit: 0,
            handing: false,
            fullscreenLoading: false,
            userName: sessionStorage.userName,
            analysisVisible: 1,
            useTimeSecond: 0,
            timer: null,
        };
    },
    created() {
        this.dialogVisible = false;
        this.isSubmit = 0;
        let paper = sessionStorage.currExamPaper;
        if (!paper) {
            this.$router.replace({ path: "/exam/index" });
        } else {
            paper = JSON.parse(paper);
            this.paperId = paper.paperId;
            this.paperTitle = paper.paperTitle;
            this.analysisVisible = paper.analysisVisible;
            console.log("this.analysisVisible", this.analysisVisible);
            this.remainSecond = this.countSecond = paper.totalTime * 60;
            this.getPaperTest(JSON.parse(paper.content));
        }
    },
    mounted() {
        window.onbeforeunload = function(e) {
            e = e || window.event;

            // 兼容IE8和Firefox 4之前的版本
            if (e) {
                e.returnValue = "关闭提示";
            }

            // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
            return "关闭提示";
        };
    },
    destroyed() {
        clearInterval(this.timer);
    },
    methods: {
        // 多选题是否选中
        isMoreTestSelected(arr) {
            let res = false;
            arr.map(item => {
                if (item) {
                    res = true;
                    return true;
                }
            });
            return res;
        },
        // 请求试题
        getPaperTest(content) {
            // 得到固定试题
            let _promise = [];
            console.log("content", content);
            if (content.fixed && JSON.stringify(content.fixed) !== "{}") {
                console.log("<---------------- 固定试题 ------------->");
                console.log("content.fixed", content.fixed);
                let test = this.$http("/api/paper/getFixedTest", {
                    params: {
                        content: content.fixed
                    }
                });
                _promise.push(test);
            }

            // 得到随机试题
            if (content.random && JSON.stringify(content.random) !== "{}") {
                console.log("<---------------- 随机试题 ------------->");
                console.log("content.random", content.random);
                let test = this.$http.post(
                    "/api/getRandomTest",
                    content.random
                );
                _promise.push(test);
            }
            let test = {};
            if (_promise.length < 1) return;
            console.log("_promise", _promise);
            // realAnswers { 类型： {id: [answer, score ], } }
            Promise.all(_promise)
                .then(values => {
                    console.log("values", values);
                    values.map(item => {
                        for (let type in item.data.data) {
                            if (!test[type]) test[type] = [];
                            if (!this.realAnswers[type])
                                this.realAnswers[type] = {};
                            test[type] = test[type].concat(
                                item.data.data[type]
                            );
                            item.data.data[type].map(test => {
                                this.realAnswers[type][test.id] = [
                                    test.answer,
                                    test.score
                                ];
                            });
                        }
                    });
                    this.paper = test;
                    console.log(
                        "------------------------------------------>\npaper : ",
                        this.paper
                    );
                    this.init();
                })
                .catch(err => {
                    this.$message.error("加载试卷失败，请重试");
                });
        },
        init() {
            let paper = this.paper;
            // 单选题
            if (paper.qst_single && paper.qst_single.length > 0) {
                this.answer.qst_single = [];
                paper.qst_single.map(item => {
                    this.answer.qst_single.push([item.id, ""]);
                });
            }
            // 多选题
            if (paper.qst_more && paper.qst_more.length > 0) {
                this.answer.qst_more = {};
                paper.qst_more.map(item => {
                    this.answer.qst_more[item.id] = [];
                });
            }
            console.log("this.answer", this.answer);
            this.startTime();
        },
        startTime() {
            let useSecond = 0;
            clearInterval(this.timer);
            this.timer = setInterval(() => {
                this.remainSecond--;
                // 5分钟自动保存
                if (useSecond % 300 == 0) {
                    this.autoSaveForm();
                }
                if (this.remainSecond < 5) {
                    if (this.remainSecond <= 0) {
                        clearInterval(this.timer);
                    }
                    this.submitForm();
                }
                useSecond++;
            }, 1000);
        },
        formatSeconds(value) {
            return formatSeconds(value);
        },
        autoSaveForm() {
            this.handing = true;
            let content = this.convertContent();
            console.log('content', content)
            this.useTimeSecond = this.countSecond - this.remainSecond;
            this.$http
                .post("/api/exam/record/save", {
                    recordId: this.recordId,
                    content: JSON.stringify(content),
                    paperId: this.paperId,
                    useTimeSecond: this.useTimeSecond,
                    isSubmit: this.isSubmit,
                    sumScore: this.sumScore
                })
                .then(({ data }) => {
                    if (data.recordId) {
                        this.recordId = data.recordId;
                        sessionStorage.currExamRecordId = data.recordId;
                    }
                    console.log("data", data);
                    if (data.code === 0) {
                        this.$message({
                            type: "success",
                            message: "自动保存成功"
                        });
                    }
                    this.handing = false;
                })
                .catch(err => {
                    console.log('err', err)
                    this.$message("自动保存失败");
                    this.handing = false;
                });
        },

        // 交卷
        submitForm() {
            if (this.isSubmit) return;
            this.$confirm(
                "请仔细检查试卷, 提交了就不可再更改, 是否交卷?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            ).then(() => {
                this.fullscreenLoading = true;
                this.handing = true;
                this.isSubmit = 1;
                let content = this.convertContent();

                console.log('content', content)
                this.sumScore = this.calcScore(this.realAnswers, content);
                this.useTimeSecond = this.countSecond - this.remainSecond;
                this.$http
                    .post("/api/exam/record/save", {
                        recordId: this.recordId,
                        content: JSON.stringify(content),
                        paperId: this.paperId,
                        useTimeSecond: this.useTimeSecond,
                        isSubmit: this.isSubmit,
                        sumScore: this.sumScore
                    })
                    .then(({ data }) => {
                        if (data.code === 0) {
                            this.$message({
                                type: "success",
                                message: "交卷成功"
                            });

                        } else {
                            this.$message("你已经提交过了，不能再提交");
                        }
                        this.handing = false;
                        this.fullscreenLoading = false;
                        this.dialogVisible = true;
                        clearInterval(this.timer);
                        window.onbeforeunload = null;
                    })
                    .catch(err => {
                        this.$message("交卷失败， 请稍后重试！");
                        this.handing = false;
                        this.fullscreenLoading = false;
                        this.isSubmit = 0;
                    });
            });
        },
        tmp() {
            alert("ok");
        },
        // 转换答题内容
        convertContent() {
            let content = {};
            content.qst_single = this.answer.qst_single;
            ///////// 解析多选题答案
            if (this.answer.qst_more) {
                content.qst_more = [];
                let qst_more = this.answer.qst_more;
                for (let testId in qst_more) {
                    let binStr = "1000000";
                    for (let i = 0; i < qst_more[testId].length; i++) {
                        if (Boolean(qst_more[testId][i]) == true) {
                            binStr =
                                binStr.slice(0, i + 1) + "1" + binStr.slice(i + 2);
                        }
                    }
                    content.qst_more.push([
                        parseInt(testId),
                        parseInt(binStr, 2)
                    ]);
                }
            }
            return content;
        },

        // 计算分数
        calcScore(realAnswers, studentAnswers) {
            let score = 0;
            for (let type in studentAnswers) {
                studentAnswers[type].map(item => {
                    let testId = item[0];
                    let answer = item[1];
                    if (realAnswers[type][testId][0] == answer) {
                        score += realAnswers[type][testId][1];
                    }
                });
            }
            return score;
        }
    }
};
</script>

<style lang="scss" scoped>
.exam {
    background: #f9f9f9;
    padding-bottom: 300px;
}

.radio,
.checkbox {
    cursor: pointer;
    padding: 1px 4px;
    input {
        cursor: pointer;
    }
}
dd {
    margin-inline-start: 15px;
}
button {
    display: block;
    padding: 4px 15px;
    text-align: center;
    cursor: pointer;
    margin: 0 auto;
}
.exam-inner {
    // color: #4f4f4f;
    max-width: 920px;
    padding: 10px;
    margin: 0 auto;
    h3 {
        text-align: center;
    }
    // .inline > div {
    // 	display: inline-block;
    // }
    .qst_single {
        .radio {
            cursor: pointer;
            // margin-right: 15px;
            input {
                cursor: pointer;
            }
        }
    }
    .qst-stem,
    option {
        .text {
            max-width: calc(100% - 50px);
        }
    }
    .option {
        margin: 4px 0;
    }
}

.answer-card {
    position: fixed;
    right: 5%;
    top: 33%;
    width: 18%;
    min-width: 210px;
    max-width: 310px;
    border: 1px solid #bbb;
    // text-overflow: auto;
    background: rgba($color: #fff, $alpha: 0.5);
    white-space: nowrap;
    z-index: 999;
    .time {
        text-align: center;
    }
    .title {
        // background: #ccc;
        text-align: center;
    }
    .content {
        padding: 4px 5px;
        .num {
            display: inline-block;
            text-align: center;
        }
        a {
            float: left;
            width: 29px;
            height: 20px;
            margin: 2px;
            // margin-right: 5px;

            // margin-bottom: 5px;
            // padding: 1px 10px;
            border: 1px solid #999;
            &:hover {
                text-decoration: none;
            }
            &.active {
                background: #bbb;
            }
        }
    }
}
.box {
    width: 300px;
    height: 300px;
    margin: 0 auto;
    border: 1px solid #ccc;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -150px;
    margin-top: -150px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex-wrap: wrap;
}
</style>

